﻿using Abp.Reflection.Extensions;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;

namespace FutureApp.EntityFramework
{
    /// <summary>
    /// Extension methods for <see cref="DbModelBuilder"/>.
    /// </summary>
    public static class FutureAppDbModelBuilderExtensions
    {
        public static void ChangePrefixTable<TEntity>(
            this DbModelBuilder modelBuilder,
            string prefix,
            string schemaName = null)
            where TEntity : class
        {
            modelBuilder.SetTableName<TEntity>(prefix, schemaName);
        }

        private static void SetTableName<TEntity>(
            this DbModelBuilder modelBuilder,
            string prefix,
            string schemaName)
            where TEntity : class
        {
            var tableName = typeof(TEntity).GetSingleAttributeOrNull<TableAttribute>()?.Name;
            tableName = tableName ?? typeof(TEntity).Name;
            if (schemaName == null)
            {
                modelBuilder.Entity<TEntity>().ToTable(prefix + tableName);
            }
            else
            {
                modelBuilder.Entity<TEntity>().ToTable(prefix + tableName, schemaName);
            }
        }
    }
}
